package com.jthink.admin.setting;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.json.FastJson;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;
import com.jthink.common.AppConfig;
import com.jthink.common.BaseController;
import com.jthink.common.model.Setting;

import java.util.ArrayList;
import java.util.List;

/**
 * 网站设置管理控制层
 */
@Path("/admin/setting")
public class SettingAdminController extends BaseController {
    private static String USE_STATIC = "site_useStatic";
    @Inject
    private SettingAdminService srv;

    public void index() {
        render("index.html");
    }

    public void findAll() {
        List<Setting> settings = srv.findAll();
        renderJson(settings);
    }

    @Before(EvictInterceptor.class)
    /**
     * 清除前台设置的缓存
     * @com.jthink.module.setting.SettingService 缓存
     *
     */
    @CacheName("setting")
    public void update() {
        String json = getRawData();
        List<JSONObject> settings = FastJson.getJson().parse(json, ArrayList.class);
        Ret ret = srv.update(settings);
        renderJson(ret);
    }

    /**
     * 支持 switch 开关的发布功能
     */
    @Before(EvictInterceptor.class)
    /**
     * 清除前台设置的缓存
     * @com.jthink.module.setting.SettingService 缓存
     *
     */
    @CacheName("setting,menu")
    public void enableStatic() {
        Ret ret = srv.updateValue(USE_STATIC, getBoolean("checked"));
        // 更新伪静态标配置 以便即时生效
        AppConfig.useStatic = Boolean.parseBoolean(srv.getValue(USE_STATIC));
        renderJson(ret);
    }
}
